package com.yqg.protection.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yqg.protection.common.Result;
import com.yqg.protection.common.interceptor.SysLog;
import com.yqg.protection.entity.Client;
import com.yqg.protection.entity.Organization;
import com.yqg.protection.entity.User;
import com.yqg.protection.mapper.OrganizationMapper;
import com.yqg.protection.service.IClientService;
import com.yqg.protection.service.IOrganizationService;
import com.yqg.protection.service.ISimInputStoreService;
import com.yqg.protection.service.IUserService;
import com.yqg.protection.utils.Constants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * OrganizationController 前端控制器
 *
 * @author zxf
 * @since 2024-01-01
 */
@RestController
@RequestMapping("/organization")
@Api(tags = "组织管理")
public class OrganizationController {

    @Resource
    private IOrganizationService organizationService;
    @Resource
    private IUserService userService;

    @Autowired
    private OrganizationMapper organizationMapper;

    @Autowired
    private IClientService clientService;

    @Autowired
    private ISimInputStoreService simInputStoreService;

//    @Autowired
//    OrganUtils organUtils;

    /**
     * 新增或者更新
     */
    @PostMapping("/edit")
    @ApiOperation("新增或更新组织")
    @SysLog("新增或者修改组织")
    @Transactional(rollbackFor = Exception.class)
    public Result save(@RequestBody Organization organization) {
        LambdaQueryWrapper<Organization> organizationQueryWrapper = new LambdaQueryWrapper<>();
        organizationQueryWrapper.eq(Organization::getName, organization.getName());
        organizationQueryWrapper.eq(Organization::getPid, organization.getPid());
        if (organizationService.getOne(organizationQueryWrapper) != null) {
            return Result.error(Constants.CODE_500, "组织名已存在");
        }
        organizationMapper.selectById(organization.getPid());
        organization.setIsDelete("0");
        organization.setCountry(1l);
        Organization organizationByPid = organizationMapper.selectById(organization.getPid());
        organizationService.saveOrUpdate(organization);
        if (organization.getLevel() == 0) {
            organization.setScTeam(organization.getId());
        } else {
            organization.setScTeam(organizationByPid.getScTeam());
            if (organization.getLevel() == 1) {
                organization.setFcTeam(organization.getId());
            } else {
                organization.setFcTeam(organizationByPid.getFcTeam());
                if (organization.getLevel() == 2) {
                    organization.setFbTeam(organization.getId());
                } else {
                    organization.setFbTeam(organizationByPid.getFbTeam());
                    if (organization.getLevel() == 3) {
                        organization.setCommunity(organization.getId());
                    } else {
                        organization.setCommunity(organizationByPid.getCommunity());
                        if (organization.getLevel() == 4) {
                            organization.setBuilding(organization.getId());
                        } else {
                            organization.setBuilding(organizationByPid.getBuilding());
                            if (organization.getLevel() == 5) {
                                organization.setUnit(organization.getId());
                            } else {
                                organization.setUnit(organizationByPid.getUnit());
                                if (organization.getLevel() == 6) {
                                    organization.setFloor(organization.getId());
                                } else {
                                    organization.setFloor(organizationByPid.getFloor());
                                    organization.setRoom(organization.getId());
                                }
                            }
                        }
                    }
                }
            }
        }
        return Result.success(organizationService.saveOrUpdate(organization));
    }

    /**
     * 删除时进行校验
     */
    @GetMapping("/delete")
    @ApiOperation("根据ID删除组织")
    @SysLog("删除组织")
    @Transactional(rollbackFor = Exception.class)
    public Result delete(@RequestParam Long organizationId) {
        LambdaQueryWrapper<Organization> organizationQueryWrapper = new LambdaQueryWrapper<>();
        organizationQueryWrapper.eq(Organization::getPid, organizationId);
        organizationQueryWrapper.eq(Organization::getIsDelete, "0");
        List<Organization> list = organizationService.list(organizationQueryWrapper);
        if (list != null && list.size() > 0) {
            return Result.error(Constants.CODE_500, "当前组织存在下级组织，请先删除下级组织");
        } else {
            LambdaQueryWrapper<User> userQueryWrapper = new LambdaQueryWrapper<>();
            userQueryWrapper.eq(User::getOrganization, organizationId);
            userService.remove(userQueryWrapper);
            LambdaQueryWrapper<Client> clientQueryWrapper = new LambdaQueryWrapper<>();
            clientQueryWrapper.eq(Client::getOrganization, organizationId);
            clientService.remove(clientQueryWrapper);
//            LambdaQueryWrapper<SimInputStore> simInputStoreQueryWrapper = new LambdaQueryWrapper<>();
//            simInputStoreQueryWrapper.eq(SimInputStore::getOrganization, organizationId);
//            simInputStoreService.remove(simInputStoreQueryWrapper);
            organizationService.removeById(organizationId);
        }
        return Result.success();
    }

    /**
     * 查询所有
     */
    @GetMapping("/all")
    @ApiOperation("查询所有组织")
    public Result findAll() {
        QueryWrapper<Organization> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", "0");
        List<Organization> list = organizationService.list(queryWrapper);
        return Result.success(list);
    }

    /**
     * 根据id查询
     */
    @GetMapping("/{id}")
    @ApiOperation("根据ID查询组织")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(organizationService.getById(id));
    }

    /**
     * 分页查询
     */
    @GetMapping("/page")
    @ApiOperation("分页查询组织")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        QueryWrapper<Organization> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", "0");
        queryWrapper.orderByDesc("id");
        return Result.success(organizationService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    /**
     * 根据id查询
     */
    @GetMapping("/findHighOrgan")
    @ApiOperation("查询最高级组织")
    public Result findHighOrgan() {
        LambdaQueryWrapper<Organization> organizationQueryWrapper = new LambdaQueryWrapper<>();
        organizationQueryWrapper.eq(Organization::getLevel, 0);
        organizationQueryWrapper.eq(Organization::getIsDelete, "0");
        return Result.success(organizationService.list(organizationQueryWrapper));
    }

    /**
     * 根据id查询
     */
    @GetMapping("/findOrganizations/{id}")
    @ApiOperation("根据父ID查询子组织")
    public Result findOrganizations(@PathVariable Integer id) {
        LambdaQueryWrapper<Organization> organizationQueryWrapper = new LambdaQueryWrapper<>();
        organizationQueryWrapper.eq(Organization::getPid, id);
        organizationQueryWrapper.eq(Organization::getIsDelete, "0");
        return Result.success(organizationService.list(organizationQueryWrapper));
    }

    @ApiOperation("导出数据")
    @GetMapping("/export")
    public void export(HttpServletResponse response) {
        organizationService.export(response);
    }
}

